$(function () {
    $("#jqGrid").jqGrid({
        url: apiBaseURL + 'sys/commLesson?lessonType=2',
        datatype: "json",
        colModel: [
            { label: '课程ID', name: 'lessonMasterId',width:60 ,sortable:false},
            { label: '课程名称', name: 'lessonName' ,width:300,sortable:false},
            { label: '教练', name: 'lessonMasterId' ,width:100,sortable:false,formatter: function(value, options, row){
                coachList = row.coachs;
                var view = "";
                for(i=0;i<coachList.length;i++){
                    view+='<span class="label label-info">'+coachList[i].coachName+'</span>'
                }
                return view;
            }},
            { label: '添加时间', name: 'createdTime',width:100,sortable:false },
            { label: '操作', name: 'lessonMasterId', width: 200,sortable:false,
                formatter: function(value, options, row){
                    //var updateBtn =  '<a  class="btn btn-primary" onclick="vm.update('+value+')"><i class="fa fa-pencil-square-o"></i>&nbsp;查看</a>';
                    var delBtn =  '<a  class="btn btn-primary" onclick="vm.del('+value+')"><i class="fa fa-pencil-square-o"></i>&nbsp;删除</a>';
                    var view =  '<a  class="btn btn-primary" onclick="vm.update('+value+')"><i class="fa fa-pencil-square-o"></i>&nbsp;详情</a>';
                    var addLessonItem =  '<a  class="btn btn-primary" onclick="vm.addLessonItem('+value+')"><i class="fa fa-pencil-square-o"></i>&nbsp;添加课程时间</a>';
                    if (row.lessonBookNums&&row.lessonBookNums>0){
                        delBtn = '';
                    }
                    return delBtn+view+addLessonItem;
                }}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });

    $('#creadTimeBeg').datetimepicker({
        autoclose: true,
        language: 'zh-CN',
        format:'yyyy-MM-dd',
        todayBtn:"linked",
        minView:2
    }).on('hide', function(e) {
        vm.q.creadTimeBeg=$('#creadTimeBeg').val();
    });
    $('#creadTimeEnd').datetimepicker({
        autoclose: true,
        language: 'zh-CN',
        format:'yyyy-MM-dd',
        todayBtn:"linked",
        minView:2
    }).on('hide', function(e) {
        vm.q.creadTimeEnd=$('#creadTimeEnd').val();
    });
    CKEDITOR.replace( 'lessonIntro', {
        removePlugins: 'sourcearea',
        width:500
    } );
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
            lessonName:null,
			lessonEnd:null,
            coachName:null,
            creadTimeBeg:null,
            creadTimeEnd:null
		},
        lessonMaster:{},
		showList: true,
        showLessonItemQ:true,
		title:null,
        coachs:null,
        lessonItem:{
            lessonBegTime:null,
            lessonEndTime:null,
            lessonMaxNums:null,
            lessonPrice:null,
            lessonMasterId:null
        },
        item_q:{
            coachId:null,
            lessonBeg:null,
            lessonEnd:null,
            lessonMasterId:null
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增团课";
			vm.lessonMaster={
                lessonMasterId:null,
                lessonName:null,
                coachs:[],
                lessonIntro:null,
                lessonAttention:null,
                lessonType:2,
                lessonPic:null
            };
			Vue.set(vm.lessonMaster,'lessonIntro','');
            this.getCoachs();
            CKEDITOR.instances.lessonIntro.setData('')
		},
		update: function (lessonMasterId) {
			vm.showList = false;
            vm.title = "团课详情";
            this.getLessonMaster(lessonMasterId);
            this.getCoachs();
		},
		del: function (lessonId) {
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "DELETE",
				    url: apiBaseURL + "sys/lesson/"+lessonId,
                    contentType: "application/json",
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(){
                                vm.reload();
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		saveOrUpdate: function () {
			var type = vm.lessonMaster.lessonMasterId == null ? "POST" : "PUT";
            vm.lessonMaster.lessonIntro = CKEDITOR.instances.lessonIntro.getData();
			$.ajax({
				type: type,
			    url: apiBaseURL + "sys/commLesson",
                contentType: "application/json",
			    data: JSON.stringify(vm.lessonMaster),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
        getLessonMaster: function(lessonMasterId){
			$.get(apiBaseURL + "sys/commLesson/"+lessonMasterId, function(r){
				vm.lessonMaster = r.lesson;
                CKEDITOR.instances.lessonIntro.setData(vm.lessonMaster.lessonIntro);
			});
		},
		reload: function () {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    lessonName:vm.q.lessonName,
                    lessonEnd:vm.q.lessonEnd,
                    coachName:vm.q.coachName,
                    creadTimeBeg:vm.q.creadTimeBeg,
                    creadTimeEnd:vm.q.creadTimeEnd,
                },
                page:page
            }).trigger("reloadGrid");
		},
        getCoachs:function () {
            $.get(apiBaseURL + "sys/coach/base", function(r){
                vm.coachs = r.coachs;
            });
        },
        onSelectedDrug:function (event,coach) {
            coach.coachId = this.coachs[parseInt(event.target.value)].coachId;
            coach.coachName = this.coachs[parseInt(event.target.value)].coachName;
        },
        addCoach:function () {
            if (this.lessonMaster.coachs){
                for (i = 0;i<this.lessonMaster.coachs;i++){
                    if (this.lessonMaster.coachs[i].coachId==null||this.lessonMaster.coachs[i].coachId==''){
                        alert("请先填写已有空白项")
                    }
                }
            }
            this.lessonMaster.coachs.push({
                coachId: null,
                coachName: null
            })
        },
        removeCoach:function (index) {
            this.lessonMaster.coachs.splice(index, 1)
        },
        saveLessonItem:function () {
            if (this.lessonItem.lessonMasterId==null||this.lessonItem.lessonMasterId==''||this.lessonItem.lessonMasterId=='undefined'){
                alert("课程信息获取失败");
                return ;
            }
            if (this.lessonItem.lessonPrice==null||this.lessonItem.lessonPrice=='undefined'||this.lessonItem.lessonPrice<0){
                alert("课程价格不能小于0");
                return ;
            }
            if (this.lessonItem.lessonMaxNums==null||this.lessonItem.lessonMaxNums=='undefined'||this.lessonItem.lessonMaxNums<1){
                alert("课程人数不能小于1");
                return ;
            }
            if (this.lessonItem.lessonBegTime==null||this.lessonItem.lessonBegTime=='undefined'||this.lessonItem.lessonEndTime==null||this.lessonItem.lessonEndTime=='undefined'){
                alert("未设置课程时间");
                return ;
            }
            $.ajax({
                type: "POST",
                url: apiBaseURL + "sys/commLesson/item",
                contentType: "application/json",
                data: JSON.stringify(vm.lessonItem),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功');
                        vm.lessonItem ={
                            lessonBegTime:null,
                            lessonEndTime:null,
                            lessonMaxNums:null,
                            lessonPrice:null,
                            lessonMasterId:vm.lessonItem.lessonMasterId
                        };
                        vm.reloadItemGrid();
                    }else{
                        alert(r.msg);
                    }
                }
            });

        },
        showLessonLayer:function (lessonMasterId) {
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "添加团课课程",
                area: ['1000px', '500px'],
                shadeClose: false,
                content: jQuery("#addLessonItem"),
                btn: ['返回']
            });
        },
        toggleQueryAdd:function () {
            vm.showLessonItemQ=!vm.showLessonItemQ;
        },
        addLessonItem:function (lessonMasterId) {
           this.lessonItem={};
           this.lessonItem.lessonMasterId=lessonMasterId;
           this.showLessonLayer(lessonMasterId);
           this.item_q.lessonMasterId=lessonMasterId;
           this.initLessonItemGrid(lessonMasterId);
           this.reloadItemGrid();
           this.showLessonItemQ=false;
            initLessonItemDatePicker();
            initLessonItemQDatePicker();
        },
        initLessonItemGrid:function(lessonMasterId){
            $("#lesson_item").jqGrid({
                url: apiBaseURL + 'sys/lesson/list?lessonType=2',
                datatype: "local",
                colModel: [
                    { label: '课程ID', name: 'lessonItemId' ,width:65,sortable:false},
                    { label: '教练', name: 'coachs' ,width:90,sortable:false,formatter: function(value, options, row){
                        coachs  = row.coachs;
                        coachView = "";
                        for (i=0;i<coachs.length;i++){
                            coachView += '<span class="label label-info">'+coachs[i].coachName+'</span>' ;
                        }
                        return coachView;
                    }},
                    { label: '课程价格', name: 'lessonPrice' ,width:65,sortable:false},
                    { label: '课程人数', name: 'lessonMaxNums' ,width:65,sortable:false},
                    { label: '预订数量', name: 'lessonBookNums' ,width:65,sortable:false},
                    { label: '开始时间', name: 'lessonBegTime',width:130,sortable:false },
                    { label: '结束时间', name: 'lessonEndTime',width:130,sortable:false },
                    { label: '添加时间', name: 'createdTime',width:130,sortable:false },
                    { label: '操作', name: 'lessonItemId', width: 120,sortable:false,
                        formatter: function(value, options, row){
                            //var updateBtn =  '<a  class="btn btn-primary" onclick="vm.update('+value+')"><i class="fa fa-pencil-square-o"></i>&nbsp;查看</a>';
                            var delBtn =  '<a  class="btn btn-primary" onclick="vm.del('+value+')"><i class="fa fa-pencil-square-o"></i>&nbsp;删除</a>';
                            if (row.lessonBookNums&&row.lessonBookNums>0){
                                delBtn = '';
                            }
                            return delBtn;
                        }}
                ],
                viewrecords: true,
                height: 200,
                rowNum: 5,
                rowList : [5,10,15],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#lesson_item_pager",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#lesson_item").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
        },
        reloadItemGrid:function () {
            var page = $("#lesson_item").jqGrid('getGridParam','page');
            $("#lesson_item").jqGrid('setGridParam',{
                postData:{
                    coachId:vm.item_q.coachId,
                    lessonBeg:vm.item_q.lessonBeg,
                    lessonEnd:vm.item_q.lessonEnd,
                    lessonMasterId:vm.item_q.lessonMasterId
                },
                datatype:'json',
                page:page
            }).trigger("reloadGrid");
        }
	}
});

function initLessonItemDatePicker() {
    $('#lessonBegTime').val('');
    $('#lessonBegTime').datetimepicker({
        autoclose: true,
        language: 'zh-CN',
        format:'yyyy-MM-dd hh:ii:00',
        startDate:new Date(),
        todayBtn:"linked",
        minView:0
    }).on('hide', function(e) {
        if (vm.lessonItem.lessonBegTime!=null){
            if (new Date(vm.lessonItem.lessonBegTime)>new Date($('#lessonEndTime').val())){
                alert("开始时间不能大于结束时间");
                $('#lessonBegTime').val('');
                return ;
            }
        }
        vm.lessonItem.lessonBegTime = $('#lessonBegTime').val();
    });
    $('#lessonEndTime').val('');
    $('#lessonEndTime').datetimepicker({
        autoclose: true,
        language: 'zh-CN',
        format:'yyyy-MM-dd hh:ii:00',
        startDate:new Date(),
        todayBtn:"linked",
        minView:0
    }).on('hide', function(e) {
        if ($('#lessonEndTime').val()){
            if (vm.lessonItem.lessonBegTime==null||vm.lessonItem.lessonEndTime==''){
                alert("请先选择开始时间");
                $('#lessonEndTime').val('');
                return;
            }
            if (new Date(vm.lessonItem.lessonBegTime)>new Date($('#lessonEndTime').val())){
                alert("开始时间不能大于结束时间");
                $('#lessonEndTime').val('');
                return ;
            }
        }
        vm.lessonItem.lessonEndTime = $('#lessonEndTime').val();
    });
}
function initLessonItemQDatePicker() {
    $('#lesson_item_beg').val('');
    $('#lesson_item_beg').datetimepicker({
        autoclose: true,
        language: 'zh-CN',
        format:'yyyy-MM-dd hh:ii:00',
        startDate:new Date(),
        todayBtn:"linked",
        minView:0
    }).on('hide', function(e) {
        if (vm.item_q.lessonEnd!=null){
            if (new Date($('#lesson_item_beg').val(''))>new Date($('#lessonEndTime').val())){
                alert("开始时间不能大于结束时间");
                $('#lesson_item_beg').val('');
                return ;
            }
        }
        vm.item_q.lessonBeg = $('#lesson_item_beg').val();
    });
    $('#lesson_item_end').val('');
    $('#lesson_item_end').datetimepicker({
        autoclose: true,
        language: 'zh-CN',
        format:'yyyy-MM-dd hh:ii:00',
        startDate:new Date(),
        todayBtn:"linked",
        minView:0
    }).on('hide', function(e) {
        if ($('#lesson_item_end').val()){
            if (vm.item_q.lessonBeg==null||vm.item_q.lessonBeg==''){
                alert("请先选择开始时间");
                $('#lesson_item_end').val('');
                return;
            }
            if (new Date(vm.item_q.lessonBeg)>new Date($('#lesson_item_end').val())){
                alert("开始时间不能大于结束时间");
                $('#lesson_item_end').val('');
                return ;
            }
        }
        vm.item_q.lessonEnd = $('#lesson_item_end').val();
    });
}